import reactLogo from '@assets/react.svg'
import { APP_NAME } from '@conf'
import { APP_MENUS } from '@conf/menu'
import { useLocation, useNavigate } from '@tanstack/react-router'
import { Layout, Menu } from 'antd'
import { useEffect, useState } from 'react'

const { Sider } = Layout

const generateCombine = function (arr) {
  const result = []

  // 只生成从第一个元素开始的连续组合
  for (let i = 2; i <= arr.length; i++) {
    const combination = arr.slice(0, i).join('/')
    result.push(combination)
  }

  return result
}

export default function AppMenu({ collapsed }) {
  const location = useLocation()
  const navigate = useNavigate()
  const paths = location.pathname.split('/')

  const [selectedKeys, setSelectedKeys] = useState(() => generateCombine(paths))
  const [openKeys, setOpenKeys] = useState(() => generateCombine(paths))

  const onClickMenu = (e) => {
    setOpenKeys(e.keyPath)
    setSelectedKeys([e.key])
    navigate({ to: e.key })
  }

  useEffect(() => {
    setOpenKeys(() => generateCombine(paths))
    setSelectedKeys(() => generateCombine(paths))
  }, [location])

  return (
    <Sider
      style={{ height: '100vh', backgroundColor: '#fff' }}
      trigger={null}
      collapsible
      collapsed={collapsed}>
      <div className="w-full h-16 flex justify-center items-center bg-[#041428]">
        {collapsed ? (
          <img src={reactLogo} alt="logo" />
        ) : (
          <h2 className="font-bold text-cyan-500">{APP_NAME}</h2>
        )}
      </div>

      <Menu
        inlineCollapsed={collapsed}
        onClick={onClickMenu}
        defaultOpenKeys={openKeys}
        defaultSelectedKeys={selectedKeys}
        // openKeys={openKeys}
        // selectedKeys={selectedKeys}
        mode="inline"
        items={APP_MENUS}
      />
    </Sider>
  )
}
